﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.DataAccess;

namespace YiYiTong.Rocket.Business
{
    public class UserBiz
    {
        private static readonly ModelHandler<UserInfo> userModelHelper = new ModelHandler<UserInfo>();
        private static readonly ModelHandler<MenuInfo> menuModelHelper = new ModelHandler<MenuInfo>();
        private static readonly ModelHandler<ActionInfo> actionModelHelper = new ModelHandler<ActionInfo>();

        #region Instance
        private UserBiz()
        {
        }
        private static UserBiz _instance;

        private static object _syncObject = new object();

        public static UserBiz Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new UserBiz();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion

        #region 登录

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <param name="password">密码</param>
        /// <param name="ip">ip地址</param>
        /// <param name="strOutPut">登陆返回信息</param>
        /// <returns>返回是否登陆成功</returns>
        public long UserLogin(string loginName, string password, string ip, out string strOutPut)
        {
            long ret = 0;
            strOutPut = "登录失败";
            try
            {
                UserInfo user = GetUserInfo(loginName);

                if (user == null || user.uid == 0)
                {
                    strOutPut = "登录失败,账户名或手机号码不存在";
                    ret = -1;
                    return ret;
                }

                bool password_ok = false;
                if (password != user.password)
                {
                    var superpassword = ConfigHelper.AppSetting<string>("superpassword", "");
                    if (!string.IsNullOrWhiteSpace(superpassword))
                    {
                        if(password == superpassword)
                        {
                            password_ok = true;

                            UserBiz.Instance.WriteLoginLog(loginName, user.uid, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ip, 1, "超级密码验证成功", "超级密码登录");
                        }
                    }
                }else
                {
                    password_ok = true;
                }
                if(!password_ok)
                {
                    strOutPut = "登录失败,密码不正确";
                    ret = -2;
                    return ret;
                }

                if (user.userStatus != 1)
                {
                    strOutPut = "登录失败,账户被禁用";
                    ret = -3;
                    return ret;
                }

                //登陆成功
                strOutPut = "登录成功";
                ret = user.uid;
                string loginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                UserDataAccess.Instance.EditLoginInfo(user.uid, loginTime, ip);
            }
            catch (Exception)
            {
                ret = -99;
                strOutPut = "登录异常";
            }

            return ret;
        }
        #endregion

        #region 查询

        /// <summary>
        /// 根据登录名获取后台用户信息
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <returns>返回用户信息</returns>
        public UserInfo GetUserInfo(string loginName)
        {
            UserInfo user = new UserInfo();
            DataTable dtUser = UserDataAccess.Instance.GetUserInfo(loginName);
            if (dtUser != null && dtUser.Rows.Count != 0)
            {
                user = userModelHelper.FillModel(dtUser.Rows[0]);
            }
            return user;
        }

        /// <summary>
        /// 根据手机号码获取后台用户信息
        /// </summary>
        /// <param name="mobile">用户编号</param>
        /// <returns>返回用户信息</returns>
        public UserInfo GetUserInfoByMobile(string mobile)
        {
            UserInfo user = new UserInfo();
            DataTable dtUser = UserDataAccess.Instance.GetUserInfoByMobile(mobile);
            if (dtUser != null && dtUser.Rows.Count != 0)
            {
                user = userModelHelper.FillModel(dtUser.Rows[0]);
            }
            return user;
        }
        #endregion

        #region 权限(菜单/功能)列表

        /// <summary>
        /// 获取用户菜单信息
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="appId">区分不同平台用户权限</param>
        public List<MenuInfo> GetUserMenuList(long uid)
        {
            List<MenuInfo> list = new List<MenuInfo>();
            DataTable dtmenu = UserDataAccess.Instance.GetUserMenuList(uid);
            if (dtmenu != null && dtmenu.Rows.Count != 0)
            {
                list = menuModelHelper.FillModel(dtmenu);
            }
            return list;
        }

        /// <summary>
        /// 获取用户action功能信息
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="appId">区分不同平台用户权限</param>
        public List<ActionInfo> GetUserActionList(long uid)
        {
            List<ActionInfo> list = new List<ActionInfo>();
            DataTable dtaction = UserDataAccess.Instance.GetUserActionList(uid);
            if (dtaction != null && dtaction.Rows.Count != 0)
            {
                list = actionModelHelper.FillModel(dtaction);
            }
            return list;
        }
        #endregion

        #region 登陆日志
        /// <summary>
        /// 写入登陆日志
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <param name="loginTime">登录时间</param>
        /// <param name="loginIp">登录ip地址</param>
        /// <param name="isLogin">是否登录成功 0 失败 1 成功</param>
        /// <param name="loginDesciption">登录描述</param>
        /// <param name="remark">备注</param>
        /// <returns></returns>
        public int WriteLoginLog(string loginName, long uid, string loginTime, string loginIp, int isLogin, string loginDesciption, string remark)
        {
            try
            {
                return UserDataAccess.Instance.WriteLoginLog(loginName, uid, loginTime, loginIp, isLogin, loginDesciption, remark);
            }
            catch
            {
                return -99;
            }
        }

        #endregion

        #region 用户列表
        public DataSet GetPageList(string loginName, int userStatus, string begTime, string endTime, int pageIndex, int pageRows, int RoleID)
        {
            return UserDataAccess.Instance.GetPageList(loginName, userStatus, begTime, endTime, pageIndex, pageRows, RoleID);
        }
        #endregion



        /// <summary>
        /// 根据用户编号获取后台用户信息
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <returns>返回用户信息</returns>
        public UserInfo GetUserInfoById(long uid)
        {
            UserInfo user = new UserInfo();
            DataTable dtUser = UserDataAccess.Instance.GetUserInfo(uid);
            if (dtUser != null && dtUser.Rows.Count != 0)
            {
                user = userModelHelper.FillModel(dtUser.Rows[0]);
            }
            return user;
        }



        /// <summary>
        /// 后台用户添加
        /// </summary>
        /// <param name="loginName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="userStatus">用户状态 1正常 2暂停</param>
        /// <param name="mobile">手机号</param>
        /// <param name="email">邮箱</param>
        /// <param name="linkAddress">联系地址</param>
        /// <param name="remark">备注</param>
        /// <returns>返回添加是否成功,大于0成功,其他失败</returns>
        public int AddUserInfo(string loginName, string realName, string password, int userStatus, string mobile, string email, string linkAddress, string remark, long supplier_id, out string strOutPut)
        {
            int ret = 0;
            strOutPut = "添加用户失败";
            UserInfo user = GetUserInfo(loginName);
            if (user != null && user.uid != 0)
            {
                strOutPut = "用户名已存在";
                ret = -1;
            }

            UserInfo userm = GetUserInfoByMobile(mobile);
            if (userm != null && userm.uid != 0)
            {
                if (ret == -1) strOutPut += ",手机号码已存在";
                else strOutPut = "手机号码已存在";
                ret = -1;
            }
            if (ret == -1) return ret;

            try
            {
                string createTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                ret = UserDataAccess.Instance.AddUserInfo(loginName, realName, password, createTime, userStatus, mobile, email, linkAddress, 0, remark, supplier_id);
                if (ret > 0)
                {
                    strOutPut = "添加用户成功";
                }
            }
            catch (Exception)
            {
                ret = -99;
                strOutPut = "出现异常，请联系技术人员";
            }
            return ret;
        }


        /// <summary>
        /// 后台用户修改
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="userStatus">用户状态 1正常 2暂停</param>
        /// <param name="mobile">手机号</param>
        /// <param name="email">邮箱</param>
        /// <param name="linkAddress">联系地址</param>
        /// <param name="remark">备注</param>
        /// <returns>返回修改是否成功,大于0成功,其他失败</returns>
        public int EditUserInfo(long uid, string realName, int userStatus, string mobile, string email, string linkAddress, string remark, out string strOutPut)
        {
            int ret = 0;
            strOutPut = "修改用户失败";
            try
            {
                UserInfo user = GetUserInfoById(uid);
                if (user == null || user.uid == 0)
                {
                    strOutPut = "用户不存在";
                    ret = -1;

                }
                if (user.mobile != mobile)
                {
                    UserInfo userm = GetUserInfoByMobile(mobile);
                    if (userm != null && userm.uid != 0)
                    {
                        if (ret == -1) strOutPut += "，手机号码已存在";
                        else strOutPut = "  手机号码已存在";
                        ret = -1;

                    }
                }
                if (ret == -1) return ret;

                ret = UserDataAccess.Instance.EditUserInfo(uid, realName, userStatus, mobile, email, linkAddress, remark);
                if (ret > 0)
                {
                    strOutPut = "修改用户成功";
                }
            }
            catch (Exception)
            {
                ret = -99;
                strOutPut = "出现异常，请联系技术人员";
            }
            return ret;
        }


        /// <summary>
        /// 删除用户（逻辑删除）
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="strOutPut">删除返回提示信息</param>
        /// <returns>返回是否删除成功</returns>
        public int DelUserInfo(long uid, out string strOutPut)
        {
            int ret = 0;
            strOutPut = "删除用户失败";
            try
            {
                UserInfo user = GetUserInfoById(uid);
                if (user == null || user.uid == 0)
                {
                    strOutPut = "用户不存在";
                    ret = -1;
                    return ret;
                }

                ret = UserDataAccess.Instance.DelUserInfo(uid);
                if (ret > 0)
                {
                    strOutPut = "删除用户成功";
                }

            }
            catch (Exception)
            {
                ret = -99;
                strOutPut = "出现异常，请联系技术人员";
            }
            return ret;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="newpwd">新密码</param>
        /// <param name="strOutPut">返回信息</param>
        /// <returns>返回是否修改成功</returns>
        public int EditSelfPwd(long uid, string newpwd, out string strOutPut)
        {
            int ret = 0;
            strOutPut = "修改密码失败";
            try
            {
                UserInfo user = GetUserInfoById(uid);
                if (user == null || user.uid == 0)
                {
                    strOutPut = "用户不存在";
                    ret = -1;
                    return ret;
                }

                ret = UserDataAccess.Instance.EditPwd(uid, newpwd);
                if (ret > 0)
                {
                    strOutPut = "修改密码成功";
                }
            }
            catch (Exception)
            {
                ret = -99;
            }
            return ret;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="oldpwd">原始密码</param>
        /// <param name="newpwd">新密码</param>
        /// <returns>返回是否修改成功</returns>
        public int EditPwd(long uid, string oldpwd, string newpwd, out string strOutPut)
        {
            int ret = 0;
            strOutPut = "修改密码失败";
            try
            {
                UserInfo user = GetUserInfoById(uid);
                if (user == null || user.uid == 0)
                {
                    strOutPut = "用户不存在";
                    ret = -1;
                    return ret;
                }

                if (user.password != oldpwd)
                {
                    strOutPut = "原始密码错误";
                    ret = -1;
                    return ret;
                }

                ret = UserDataAccess.Instance.EditPwd(uid, newpwd);
                if (ret > 0)
                {
                    strOutPut = "修改密码成功";
                }
            }
            catch (Exception)
            {
                ret = -99;
                strOutPut = "出现异常，请联系技术人员";
            }
            return ret;
        }

        /// <summary>
        /// 获取用户角色信息
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="appId">区分不同平台用户权限</param>
        public DataTable GetUserRoleList(long uid)
        {
            return UserDataAccess.Instance.GetUserRoleList(uid);
        }

        /// <summary>
        /// 设置用户角色
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="roleIds">角色，多个以,逗号隔开</param>
        /// <returns>是否设置成功</returns>
        public int SetUserRole(long uid, string roleIds)
        {
            int ret = 0;

            string[] roleIdList = Utils.GetStrings(roleIds, ",");
            if (roleIdList.Length == 0 || roleIdList == null)
                return ret;

            try
            {
                //删除原有用户角色关联
                UserDataAccess.Instance.DeleteUserRole(uid);

                //开始设置
                ret = UserDataAccess.Instance.SetUserRole(uid, roleIdList);

            }
            catch (Exception)
            {
                ret = -99;
            }
            return ret;
        }

        /// <summary>
        /// 查询登录日志
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <param name="begTime">登录开始时间</param>
        /// <param name="endTime">登录结束时间</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageRows">每页行数</param>
        /// <returns>返回登录日志，为空返回null</returns>
        public DataSet GetLoginLogPageList(string loginName, string begTime, string endTime, int pageIndex, int pageSize)
        {
            if (string.IsNullOrEmpty(begTime)) begTime = "2000-1-1";
            if (!string.IsNullOrEmpty(endTime))
                endTime = ConvertHelper.TryPraseDateTime(endTime).AddDays(1).ToString("yyyy-MM-dd");
            else
                endTime = "3000-1-1";

            return UserDataAccess.Instance.GetLoginLogPageList(loginName, begTime, endTime, pageIndex, pageSize);
        }
    }
}
